package manager.utility.thread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.ByteBuffer;

import manager.utility.LazyPersistedQueue;

public class UDPServerThread extends Thread {

	private DatagramSocket serverSocket;
	private final static int port = 9876;
	private final static int dimPackage = 1024;
	private byte[] receiveData;
	private LazyPersistedQueue lpq;
	
	public UDPServerThread(LazyPersistedQueue lpq) {
		this.lpq= lpq;
	}

	public void run() {
		receiveData = new byte[dimPackage];
		try {		
			serverSocket = new DatagramSocket(port);
			while(true)
			{
				DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
				serverSocket.receive(receivePacket);
				byte[] b = receivePacket.getData();
				ByteBuffer bb = ByteBuffer.allocate(b.length); 
				bb.put(b);
				System.out.println("receive packet...");
				lpq.enqueue(bb);
				//TODO: li elimino solo quando sono certo di averli memorizzati nel log?
				lpq.dequeue();
			}
			} catch (SocketException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			finally{
				if(serverSocket!=null)
					if(!serverSocket.isClosed())
						serverSocket.close();
			}
	}


	
	public void closeSocket(){
		if(serverSocket!=null)
			if(!serverSocket.isClosed())
				serverSocket.close();
	}
	
}
